//
//  DetailViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/22.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "DetailViewController.h"

#import "define.h"
#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "SightDetailViewController.h"
#import "DKNightVersion.h"
#import "AFNetworking.h"
#import "ScrollTableViewCell.h"
#import "Reachability.h"
#import "CityDetailViewController.h"
@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) NSMutableArray *imageArr;
@property (nonatomic, retain) NSDictionary *dic;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, retain) AFHTTPRequestOperationManager *man;


@end

@implementation DetailViewController

- (void)dealloc
{
    [_table release];
    [_array release];
    [_scroll release];
    [_imageArr release];
    [_dic release];
    [_man release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.imageArr = [NSMutableArray array];
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
        self.man = [[AFHTTPRequestOperationManager alloc] init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self beginConnection];
    [self createTableView];

    self.automaticallyAdjustsScrollViewInsets = NO;
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    
    self.title = @"热门城市";
    // Do any additional setup after loading the view.
}

- (void)back:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}


- (void)beginConnection
{

    NSArray *addArr = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *ppp = [addArr firstObject];
    NSString *path = [NSString stringWithFormat:@"%@/%@", ppp, self.tid];
    BOOL net = [DetailViewController judgeConnect];
    if (net) {
    NSDictionary *dic = @{@"lat":@"38.88268566409049",
                          @"lon":@"121.5391764987836",
                          @"country_id":self.tid,
                          @"page":@"1",
                          @"v":@"1",
                          @"count":@"20",
                          @"client_id":@"qyer_ios",
                          @"client_secret":@"cd254439208ab658ddf9",
                          @"track_os":@"ios%25208.4",
                          @"track_deviceid":@"2CC19978-A0E5-49F2-9719-59DC5EDE6BBB",
                          @"track_device_info":@"iPhone%25205s",
                          @"track_app_version":@"6.6"
                          };
    [self.man GET:CLASS_DETAIL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        self.dic = [responseObject objectForKey:@"data"];
        if ([[responseObject objectForKey:@"data"]isKindOfClass:[NSDictionary class]]) {
            
        
        NSArray *arr = [[responseObject objectForKey:@"data"] objectForKey:@"hot_city"];
        NSArray *daa = [[responseObject objectForKey:@"data"]objectForKey:@"photos"];
        [self.array addObjectsFromArray:arr];
        
        if (daa != nil) {
            
            
            [self.imageArr addObject:[daa lastObject]];
            [self.imageArr addObjectsFromArray:daa];
            [self.imageArr addObject:[daa firstObject]];
        }
        [self.table reloadData];
        //        [self createTableView];
        [self createScroll];
        
        NSDictionary *dic = responseObject;
        [dic writeToFile:path atomically:YES];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
        
    }else
    {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
        self.dic = [dic objectForKey:@"data"];
        NSArray *arr = [[dic objectForKey:@"data"] objectForKey:@"hot_city"];
        NSArray *daa = [[dic objectForKey:@"data"]objectForKey:@"photos"];
        [self.array addObjectsFromArray:arr];
        if (daa != nil) {
            
            
            [self.imageArr addObject:[daa lastObject]];
            [self.imageArr addObjectsFromArray:daa];
            [self.imageArr addObject:[daa firstObject]];
        }
        [self.table reloadData];
        //        [self createTableView];
        [self createScroll];
        
    }
     

}

+ (BOOL)judgeConnect
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus sta = [reach currentReachabilityStatus];
    if (sta == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}

- (void)timerAction:(NSTimer *)timer
{
    
    if (_scroll.contentOffset.x == self.view.frame.size.width * (self.imageArr.count - 2) ) {
        
        _scroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }else
    {
        
        _scroll.contentOffset = CGPointMake(_scroll.contentOffset.x + self.view.frame.size.width, 0);
    }
}



- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.table ];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.table release];

    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return self.array.count / 2;
    }else
    {
        if (self.array.count == 0) {
            return 0;
        }else
        {
        return 1;
        }
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        ScrollTableViewCell *scro = [tableView dequeueReusableCellWithIdentifier:@"scro"];
        if (self.imageArr.count != 0) {
        if (scro == nil) {
            scro = [[ScrollTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"scro"];
        
            scro.array = self.imageArr;
            scro.dic = self.dic;
        }
        
        }
    }
    if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"all"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"all"];
            if (self.array.count != 0) {
                
            cell.textLabel.text =[[self.dic objectForKey:@"cnname"] stringByAppendingString:@"城市"];
            cell.textLabel.textColor = [UIColor darkGrayColor];
            UILabel *all = [[UILabel alloc]initWithFrame:CGRectMake(280 *_offWidth, 10*_offHeight, 80*_offWidth, 30*_offHeight)];
            [cell.contentView addSubview:all];
            all.textColor = [UIColor lightGrayColor];
            all.font = [UIFont systemFontOfSize:13];
            all.text = @"查看全部";
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    if (indexPath.section == 2) {
        
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        
        UIImageView *imagel = [[UIImageView alloc]initWithFrame:CGRectMake(0, 10*_offHeight, self.view.frame.size.width / 2, 120*_offHeight)];
        [cell.contentView addSubview:imagel];
        
        UITapGestureRecognizer *tapl = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(next:)];
        [imagel addGestureRecognizer:tapl];
        imagel.tag = indexPath.row * 2;
        imagel.userInteractionEnabled = YES;
       
        [imagel sd_setImageWithURL:[NSURL URLWithString:[[self.array objectAtIndex:indexPath.row * 2]objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake((imagel.frame.size.width - 80 *_offWidth) / 2, 30*_offHeight, 80*_offWidth, 40*_offHeight)];
        [imagel addSubview:name];
        name.textColor = [UIColor whiteColor];
        name.textAlignment = 1;
        name.font = [UIFont systemFontOfSize:20];
        name.text = [[self.array objectAtIndex:indexPath.row * 2]objectForKey:@"cnname"];
        [name release];
        UIImageView *imager = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 10*_offWidth, 10*_offHeight, self.view.frame.size.width / 2, 120*_offHeight)];
        [cell.contentView addSubview:imager];
        UITapGestureRecognizer *tapr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(next:)];
        [imager addGestureRecognizer:tapr];
        imager.tag = indexPath.row * 2 + 1;
        imager.userInteractionEnabled = YES;
        
        [imager sd_setImageWithURL:[NSURL URLWithString:[[self.array objectAtIndex:indexPath.row * 2 + 1]objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        UILabel *namer = [[UILabel alloc]initWithFrame:CGRectMake((imager.frame.size.width - 80*_offWidth) / 2, 30*_offHeight, 80*_offWidth, 40*_offHeight)];
        [imager addSubview:namer];
        namer.textColor = [UIColor whiteColor];
        namer.textAlignment = 1;
        namer.font = [UIFont systemFontOfSize:20];
        namer.text = [[self.array objectAtIndex:indexPath.row * 2 + 1]objectForKey:@"cnname"];
        [namer release];

        
    }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
    return cell;
    }else
    {
        return [[[UITableViewCell alloc]init]autorelease];
    }
}

- (void)next:(UITapGestureRecognizer *)button
{
    CityDetailViewController *city = [[CityDetailViewController alloc]init];
    city.cityId = [[self.array objectAtIndex:button.view.tag]objectForKey:@"id"];
    [self.navigationController pushViewController:city animated:YES];
}

- (void)createScroll
{
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250*_offHeight)];
    
    _scroll.delegate = self;
   [self.table addSubview:self.scroll];
    _scroll.contentSize = CGSizeMake(self.imageArr.count * _scroll.frame.size.width, 0);
    _scroll.pagingEnabled = YES;
    _scroll.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
    [self createImage];
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(20*_offWidth, 100*_offHeight, self.view.frame.size.width, 50*_offHeight)];
    
    [self.table addSubview:name];
    name.textColor = [UIColor whiteColor];
    name.font = [UIFont boldSystemFontOfSize:30];
    name.text = [self.dic objectForKey:@"cnname"];
    [name release];
    UILabel *engname = [[UILabel alloc]initWithFrame:CGRectMake(20*_offWidth, 150*_offHeight, 100*_offWidth, 50*_offHeight)];
    [self.table addSubview:engname];
    engname.textColor = [UIColor whiteColor];
    engname.text = [self.dic objectForKey:@"enname"];
    [engname release];
    UILabel *language = [[UILabel alloc]initWithFrame:CGRectMake(20*_offWidth, 200*_offHeight, 300*_offWidth, 50*_offHeight)];
    [self.table addSubview:language];
    language.textColor = [UIColor whiteColor];
    language.numberOfLines = 2;
    language.font = [UIFont systemFontOfSize:15];
    language.text = [self.dic objectForKey:@"entryCont"];
    [language release];
    [_scroll release];
    
    
}

- (void)createImage
{
    for (int i = 0; i < self.imageArr.count; i++) {
        UIImageView *iamge = [[UIImageView alloc]initWithFrame:CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, self.scroll.frame.size.height)];
        
        [self.scroll addSubview:iamge];
        [iamge sd_setImageWithURL:[NSURL URLWithString:[self.imageArr objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        [iamge release];
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 250 *_offHeight  ;
    }if (indexPath.section == 1) {
        return 50*_offHeight;
    }else{
        
        return 140 *_offHeight;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scroll) {
        if (scrollView.contentOffset.x == self.scroll.frame.size.width * (self.imageArr.count - 1)) {
            
            scrollView.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
        }
        if (scrollView.contentOffset.x == 0) {
            scrollView.contentOffset = CGPointMake(self.scroll.frame.size.width * (self.imageArr.count - 2), 0);
        }
    }
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        
    
    SightDetailViewController *sight = [[SightDetailViewController alloc]init];
    sight.sid = self.tid;
    [self.navigationController pushViewController:sight animated:YES];
    
    [sight release];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
